package com.relsell.view;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;

import com.relsell.admin.DbHelper;
import com.relsell.pointofsales.GPSTracker;
import com.relsell.pointofsales.R;
import com.relsell.utility.AppVars;

/**
 * Submit Sales class that is used to submit data regarding products.
 * 
 */
public class SubmitSales extends Fragment implements OnClickListener,
		OnItemSelectedListener {

	Spinner spinner1, spinner2;
	ArrayAdapter<String> adapter1;
	ArrayAdapter<CharSequence> adapter2;
	Button bn, bn2;
	String product, quantity;
	GPSTracker gpsTracker;
	double latitude, longitude;
	List<String> li;

	public SubmitSales() {
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View v = inflater.inflate(R.layout.submitsales, container, false);
		bn = (Button) v.findViewById(R.id.btnSubmit);
		bn2 = (Button) v.findViewById(R.id.buttonClear);
		spinner1 = (Spinner) v.findViewById(R.id.spinner1);
		bn.setOnClickListener(this);
		bn2.setOnClickListener(this);

		li = new ArrayList<String>();
		li.add("A.C");
		li.add("Washing Machine");
		li.add("Refregerator");
		li.add("Oven");
		li.add("Vacuum Cleaner");
		li.add("Projector");
		li.add("Dish Washer");
		li.add("Laptop");
		li.add("Mobile Phones");
		loadSpinnerData();

		spinner2 = (Spinner) v.findViewById(R.id.spinner2);
		adapter2 = ArrayAdapter.createFromResource(this.getActivity(),
				R.array.number_arrays, android.R.layout.simple_list_item_1);
		adapter2.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
		spinner2.setAdapter(adapter2);
		spinner2.setOnItemSelectedListener(this);
		return v;

	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
	}

	@Override
	public void onClick(View arg0) {

		switch (arg0.getId()) {
		case R.id.btnSubmit:

			
			if (AppVars.isDbBackUpEnabled) {
				AppVars.dbBackup(getActivity());
			}

			gpsTracker = new GPSTracker(this.getActivity());
			if (gpsTracker.canGetLocation()) {
				latitude = gpsTracker.getLatitude();
				longitude = gpsTracker.getLongitude();
				Toast.makeText(
						this.getActivity(),
						"Your Location is - \nLat: " + latitude + "\nLong: "
								+ longitude, Toast.LENGTH_LONG).show();

				if (latitude != 0 && longitude != 0) {
					this.getActivity().setProgressBarIndeterminateVisibility(
							true);
					new SendProduct().execute();
				}

			} else {
				gpsTracker.showSettingsAlert();
			}

			break;

		case R.id.buttonClear:
			spinner1.setSelection(0);
			spinner2.setSelection(0);
			break;

		}

	}

	@Override
	public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
			long arg3) {

		Spinner spinner = (Spinner) arg0;
		if (spinner.getId() == R.id.spinner1) {
			spinner1.setSelection(arg2);
			product = (String) spinner1.getSelectedItem();
		} else if (spinner.getId() == R.id.spinner2) {

			spinner2.setSelection(arg2);
			quantity = (String) spinner2.getSelectedItem();
		}

	}

	@Override
	public void onNothingSelected(AdapterView<?> arg0) {

	}

	public class SendProduct extends AsyncTask<Void, Void, Boolean> {

		String responseString;

		@Override
		protected void onPreExecute() {
			super.onPreExecute();

		}

		@Override
		protected Boolean doInBackground(Void... params) {
			try {

				HttpClient http = new DefaultHttpClient();
				String server = AppVars.getServer();
				HttpPost post = new HttpPost("http://" + server
						+ "/gcminteraction/view/start.php?controlVar=3");
				List<NameValuePair> data = new ArrayList<NameValuePair>();
				Log.w("Product", product);
				Log.w("Product", quantity);
				data.add(new BasicNameValuePair("producttype", product));
				data.add(new BasicNameValuePair("productquantity", quantity));
				data.add(new BasicNameValuePair("lat", String.valueOf(latitude)));
				data.add(new BasicNameValuePair("long", String
						.valueOf(longitude)));
				post.addHeader("loggedinuserid", AppVars.sloggedInUserId);
				post.setEntity(new UrlEncodedFormEntity(data));

				HttpResponse response = http.execute(post);

				responseString = new BasicResponseHandler()
						.handleResponse(response); // Basic handler
				if (AppVars.isLogEnabled) {
					Log.v(AppVars.LOG_TAG, "Response String =" + responseString);
				}
				// result = obj.getString("loggedIn");

				return true;
			} catch (ClientProtocolException e) {

			} catch (IOException e) {

			}
			return false;
		}

		@Override
		protected void onPostExecute(Boolean success) {
			
			DbHelper helper = new DbHelper(getActivity());
			helper.open();
			helper.insert_product_data(product);
			helper.close();

			getActivity().setProgressBarIndeterminateVisibility(false);
			Toast.makeText(getActivity(), "Products Submitted",
					Toast.LENGTH_LONG).show();
		}
	}

	private void loadSpinnerData() {
		// database handler
		DbHelper db = new DbHelper(getActivity());
		db.open();
		// Spinner Drop down elements
		List<String> lables = db.read_product_data();
		db.close();
		Log.w("values",lables.toString());
         li.addAll(lables);
		adapter1 = new ArrayAdapter<String>(this.getActivity(),
				android.R.layout.simple_dropdown_item_1line, li);

		adapter1.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
		spinner1.setAdapter(adapter1);
		//spinner1.setAdapter(adapter3);
		spinner1.setOnItemSelectedListener(this);
	}

}
